/* eslint-disable no-use-before-define */
import type { AxiosProgressEvent } from 'axios';
import axios, { type Response } from '@/utils/axios/axios';

/**
 * 上传文件
 */
export async function uploadAxios(data: { file: File; onUploadProgress?: (res: AxiosProgressEvent) => void; url?: string }): Promise<UploadResponse> {
  try {
    const uploadURL = data.url || `${import.meta.env.VITE_BASE_UPLOAD_URL}/upload/uploadFile`;
    const formData = new FormData();
    formData.append('file', data.file);
    const res = (await axios.post(uploadURL, formData, {
      timeout: 1000 * 60 * 60 * 12,
      headers: { 'Content-Type': 'multipart/form-data' },
      onUploadProgress: data.onUploadProgress,
    })) as unknown as Response<UploadResponse>;
    return Promise.resolve(res.data);
  } catch (error) {
    return Promise.reject(error);
  }
}

/**
 * 得到七牛云的上传 token
 */
export function getQnUptokenAxios(data: { md5: string; folder: string; fileName: string; fileType: string }): Promise<Response<string>> {
  return axios.post(`${import.meta.env.VITE_BASE_UPLOAD_URL}/upload/getToken`, data) as unknown as Promise<Response<string>>;
}

export type UploadResponse = {
  /** 文件MD5 */
  fileHash?: string;
  /** 图片或视频URL */
  url: string;
  /** 地一帧图片 */
  frameUrl?: string;
  /** 图片或视频宽度 */
  width?: number;
  /** 图片或视频高度 */
  height?: number;
  /** 图片或视频大小 */
  size?: number;
};
